//
//  YDBScanBluViewController.swift
//  DKE-Album
//
//  Created by dagny on 2025/9/20.
//  Copyright © 2025 杨东宝. All rights reserved.
//

import Foundation
import SwiftyGif
import EmptyDataSet_Swift
//委托协议
protocol YDBScanViewControllerDelegate: AnyObject {
    //刷新
    func didSelectDevice(deviceModel:DeviceModel);
    
}
class YDBScanViewController: YDBBaseViewController{
    
    var deviceListViewModel = DeviceListViewModel.init();
    var delegate:YDBScanViewControllerDelegate?
    // 创建自定义搜索框实例
    let searchBar = CustomSearchBar()
    
    //MARK:- 搜素按钮
    lazy var scanBtn: UIButton = {
        let btn =  UIButton.init(type: .custom)
        btn.setTitle("scan_btn_title".localized, for: .normal)
        btn.setTitle("stop_scan_btn_title".localized, for: .selected)
        btn.setTitleColor(HexRGB(0x3D4466), for: .normal)
        btn.titleLabel?.font = DIMENSION_FONT_OF_SIZE(14)
        btn.addTarget(self, action: #selector(scanBtnClick(_ : )), for: .touchUpInside)
        view.addSubview(btn)
        return btn
    }()
    //MARK: - loading按钮
    lazy var loadingBtn:ContentButton = {
        let messageBtn = ContentButton.init(frame: CGRect(x: DIMENSION_VALUE(10), y: DIMENSION_VALUE(5), width: DIMENSION_VALUE(30), height: DIMENSION_VALUE(30)))
        view.addSubview(messageBtn)
        return messageBtn
    }()
    //MARK:- 提示按钮
    lazy var label3: UILabel = {
        let label = UILabel()
        label.text = "loading_title_load".localized
        label.font = DIMENSION_FONT_OF_SIZE(16)
        label.textColor = HexRGB(0x3D4466)
        view.addSubview(label)
        return label
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "deivice_list".localized
        deviceListViewModel.delegate = self
        searchBar.translatesAutoresizingMaskIntoConstraints = false
                view.addSubview(searchBar)
        view.addSubview(searchBar)
        deviceListViewModel.onStateUpdate = { [weak self] state in
            self?.onstates(state: state)
        }
        searchBar.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
            make.right.equalToSuperview().offset(DIMENSION_VALUE(-10))
            make.top.equalToSuperview().offset(DIMENSION_VALUE(5))
            make.height.equalTo(DIMENSION_VALUE(40))
        }
        setupSearchBar()
        
        scanBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(DIMENSION_VALUE(-10))
            make.top.equalTo(searchBar.snp_bottom).offset(DIMENSION_VALUE(5))
            make.height.equalTo(DIMENSION_VALUE(30))
        }
        label3.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
            make.centerY.equalTo(scanBtn.snp_centerY)
        }
        loadingBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
            make.centerY.equalTo(label3.snp_centerY)
            make.width.height.equalTo(DIMENSION_VALUE(30))
        }
        tableView.register(DeviceListCell.self, forCellReuseIdentifier: "DeviceListCell")
        self.view.addSubview(self.tableView);
        tableView.myh_footer?.isHidden = true
        tableView.myh_header?.isHidden = true
        tableView.snp.makeConstraints { make in
            make.top.equalTo(scanBtn.snp_bottom).offset(DIMENSION_VALUE(5))
            make.left.right.bottom.equalToSuperview()
        }
    }
    //状态监听
    func onstates(state:ConectState){
         switch state {
         case .poweredOff:
             stopScanLoading()
             break //蓝牙关闭
         case .poweredOn:
             scanBtn.isSelected = false
             scanBtnClick(scanBtn)
             break//蓝牙开启
         default: break
         }
    }
      private func setupSearchBar() {
          // 自定义搜索框外观
          searchBar.placeholder = "input text"
          searchBar.cornerRadius = DIMENSION_VALUE(20)
          searchBar.borderColor = HexRGB(0xeeeeee)
          searchBar.searchIconColor = HexRGB(0xeeeeee)
          searchBar.clearButtonColor = HexRGB(0xeeeeee)
          // 设置代理
          searchBar.delegate = self
      }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        scanBtnClick(scanBtn)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        stopScanLoading()
    }
}
extension YDBScanViewController{
    
    //MARK: - 点击扫描按钮
    @objc func scanBtnClick(_ btn :UIButton) {
        if  scanBtn.isSelected{
            scanBtn.isSelected = false
            stopScanLoading()
        }else{
            scanBtn.isSelected = true
            startScanLoading()
        }
    }
    
    func startScanLoading(){
        loadingBtn.content = .inProgress
        deviceListViewModel.startScan(fileName:searchBar.text)
        label3.text = "loading_title_load".localized
        label3.snp.updateConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(50))
        }
    }
    func stopScanLoading(){
        deviceListViewModel.stopScan()
        label3.text = "loading_title_complate".localized
        loadingBtn.content = .default
        label3.snp.updateConstraints { make in
            make.left.equalToSuperview().offset(DIMENSION_VALUE(10))
        }
    }
}
// 实现搜索框代理方法
extension YDBScanViewController: CustomSearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: CustomSearchBar) {
        searchBar.resignActive()
        scanBtn.isSelected = false
        scanBtnClick(scanBtn)
    }

    func searchBarClearButtonClicked(_ searchBar: CustomSearchBar) {
        searchBar.resignActive()
        scanBtn.isSelected = false
        scanBtnClick(scanBtn)
    }
}
extension YDBScanViewController{
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return  deviceListViewModel.bluList.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell : DeviceListCell = tableView.dequeueReusableCell(withIdentifier: "DeviceListCell") as! DeviceListCell
        cell.model = deviceListViewModel.bluList[indexPath.row]
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let deviceModel = deviceListViewModel.bluList[indexPath.row]
        delegate?.didSelectDevice(deviceModel: deviceModel)
        userManger.addDeviceModel(deviceModel: deviceModel)
        deviceListViewModel.stopScan()
    }
}
extension YDBScanViewController:EmptyDataSetSource,EmptyDataSetDelegate{
    func customView(forEmptyDataSet scrollView: UIScrollView) -> UIView? {
        let customView = UIView();
        return customView
    }
}
extension YDBScanViewController:DeviceListViewModelDelegate{
    func refresh() {
        self.tableView.reloadData()
    }
}


